import axios from "axios";
import Web3 from "web3";
import router from "@/router";
import { Message } from "element-ui";

var web3 = new Web3();

// const uri = process.env.NODE_ENV === "development" ? '/api/' : 'http://45.249.247.134:8086';
// const uri =  process.env.NODE_ENV === "development"?'/api/':'http://admin.jogger.cc/'
const uri = process.env.NODE_ENV === "development" ? "/api/" : "";

const url1 = uri+'/public'
// const url1 = uri + "/login";
const url2 = uri + "/api";

const instance = axios.create({
  timeout: 50000,
});
instance.interceptors.request.use(
  function (config) {
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response;
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export function ajaxPost(method, params) {
	console.log(params);
  let tt = new Date().getTime().toString();
  let reqId = tt.substring(tt.length - 5, tt.length);
  params = web3.utils.toHex(params);
  var jsons = {
    reqId: parseInt(reqId),
    method: method,
    data: params,
  };
  let toHexstr = web3.utils.toHex(jsons);
  const isflag = method.toLowerCase();
  return instance({
    url: isflag.indexOf("admin") > -1 ? url1 : url2,
    method: "post",
    data: {
      reqRaw: toHexstr,
    },
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "AccessToken-Agent": localStorage.getItem("adminToken") || "",
    },
  })
    .then((res) => {
      let { response, data } = res.data;
      if (response.errCode == 0) {
        return res.data;
      } else if (response.errCode == 1003) {
        Message.error(res.data.response.msg);
        return { data: {}, response: {} };
      } else if (response.errCode == 1008) {
        localStorage.removeItem("adminToken");
        localStorage.removeItem("role");
        localStorage.removeItem("UserName");
        router.push({ path: "/login" });
        Message.error(res.data.data);
        return { data: {}, response: {} };
      }
    })
    .catch((err) => {
      console.log(err);
      Message.error(err.message);
      return { data: {}, response: {} };
    });
}

export function website(addr) {
  return axios.get("https://www.kortho.io/website/getBalance?address=" + addr);
}

export default instance;
